import { AppGlobalService } from './../../shared/service/app-global.service';
import { Component, Input, OnInit } from '@angular/core';
import { EventService } from 'src/app/shared/service/event.service';
import { HttpService } from 'src/app/shared/service/http.service';
import { ActionSheetController, AlertController, ModalController } from "@ionic/angular";
import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { ShareService } from 'src/app/shared/service/share.service';
import { VideoImgPopupComponent } from '../video-img-popup/video-img-popup.component';
// tslint:disable
declare let $: any;
@Component({
  selector: 'app-comments-list',
  templateUrl: './comments-list.component.html',
  styleUrls: ['./comments-list.component.scss'],
})
export class CommentsListComponent implements OnInit {

  @Input() tagData: any;
  showLoadMore = false;
  pageNo = 1;
  pageSize: number;
  pageTotal: number;
  // 筛选及页面数据参数
  params: any = { content: {} };
  phoneArray = [];
  ids: any;
  hint = '暂无数据';

  constructor(
    private pageModalService: PageModalService,
    private appGlobalService: AppGlobalService,
    private actionSheetCtrl: ActionSheetController,
    private shareService: ShareService,
    public alertController: AlertController,
    private httpService: HttpService,
    private eventService: EventService,
    public modalController: ModalController,
  ) {



    // 监听多选后
    if (this.eventService.eventEmit.listenerCount('chooseAll') > 0) {
      this.eventService.eventEmit.removeListener('chooseAll');
    }
    // 全选
    this.eventService.eventEmit.on('chooseAll', res => {
      if (res) {
        this.tagData.data.data.forEach(element => {
          element.checked = true;
        });
      } else {
        this.tagData.data.data.forEach(element => {
          element.checked = false;
        });
      }
    });
    // 监听多选后
    if (this.eventService.eventEmit.listenerCount('auditNow') > 0) {
      this.eventService.eventEmit.removeListener('auditNow');
    }

    this.eventService.eventEmit.on('auditNow', res => {
      console.log(res);
      const ids = [];
      this.tagData.data.data.forEach(element => {
        if (element.check === 'true' && element.checked) {
          ids.push(element.id);
        }
      });
      if (ids.length === 0) {
        this.ids = '';
        return;
      }
      this.ids = ids.join(',');

      if (res.target) {
        this.showModal(res);
      } else {
        // submit
        this.presentAlertWithMsgBtn(res);

      }

    });
  }
  openImg(imgs, i, e) {
    if(e) {
      e.stopPropagation();
    }
    this.pageModalService.openImage_url(i, imgs);
  }
  showModal(link) {
    const that = this;
    if (link.type === 'pageModal') {
      link.params.id = this.ids;
      link.modalCss = 'auto-modal';
      this.pageModalService.openPage(link, '', result => {
        if (result) {
          that.updateItem();
        }
      });
    }
  }


  async presentAlertWithMsgBtn(submit) {
    const that = this;
    const alert = await this.alertController.create({
      message: submit.text,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: '确定',
          handler: () => {
            submit.content.user_evaluate_id = this.ids;
            const params = {
              content: submit.content,
              id: submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              if (res.success) {
                this.appGlobalService.showToast(res.message, 1500, "middle");

                if (submit.content.needDel) {

                  for (let i = this.tagData.data.data.length - 1; i >= 0; i--) {
                    if (this.tagData.data.data[i].checked) {
                      this.tagData.data.data.splice(i, 1);
                    }
                  }
                  this.ids = '';
                  this.checkAll();

                } else {
                  that.updateItem();
                }


              }
            });
          }
        }
      ]
    });
    await alert.present();
  }

  ngOnInit() {

    if (this.tagData && this.tagData.hint) {
      this.hint = this.tagData.hint;
    }
    const listTagName = this.tagData.name + 'AskForList';
    this.eventService.eventEmit.on(listTagName, (obj) => {
      this.refreshListData(obj);
    });
    this.pageTotal = this.tagData.pageTotal;
    this.pageNo = this.tagData.pageNo;
    this.pageSize = this.tagData.pageSize;
    this.params.content = this.tagData.data.submit;
    this.params.sessionId = localStorage.getItem("sessionId");
    this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize));


    const description = document.getElementById("html2canvas");
    this.tagData.data.data.forEach(element => {

      description.innerHTML = element.thirdLeft? element.thirdLeft.firstText.label : '';
      description.style.width = '100VW';
      description.style.padding = '0 1rem';
      description.style.fontSize = '0.94rem';
      description.style.lineHeight = '1.31rem';
      const n = description.offsetHeight;
      if (n <= 63) {
        element.showText = '';
      } else {
        element.showText = '查看全部';
      }
    });
    description.innerHTML = '';

    const singleDataTagName = this.tagData.name + 'singleData';
    if (this.eventService.eventEmit.listenerCount(singleDataTagName) > 0) {
      this.eventService.eventEmit.removeListener(singleDataTagName);
    }
    this.eventService.eventEmit.on(singleDataTagName, (res) => {
      this.addSingleData(res);
    });

    if (this.eventService.eventEmit.listenerCount('delItemCommentsList') > 0) {
      this.eventService.eventEmit.removeListener('delItemCommentsList');
    }
    this.eventService.eventEmit.on('delItemCommentsList', (res) => {
      if (this.appGlobalService.commentsListIndex !== undefined && this.appGlobalService.commentsListIndex !== '') {
        this.tagData.data.data.splice(this.appGlobalService.commentsListIndex, 1);
        this.appGlobalService.commentsListIndex = '';
      }
    });

  }

  addSingleData(param) {
    setTimeout(() => {
      const arr = param.result.split(',');
      param[param['key']] = arr[0];

      this.httpService.post('application/part', {
        viewId: arr[1],
        sessionId: localStorage.getItem("sessionId"),
        params: param,
      }, res => {
        try {
          const tagData = res.script?JSON.parse(res.script).tags[0].currentData.tags[0] : '';
          if (tagData.data.data) {
            // submit.id 相同 说明数据源相同
            if(tagData.data.submit.id && this.tagData.data.submit.id && tagData.data.submit.id === this.tagData.data.submit.id) {
              this.tagData.data.data.unshift(tagData.data.data[0]);
            }
          }
        } catch (error) {
          console.log(error);
        }

      });
    }, 800);
  }

  refreshListData(param) {
    const that = this;
    if (param === undefined) {
      return;
    }
    this.pageNo = 1;
    if (param.showName !== undefined) {
      if (this.tagData.data.submit.content.showName) {
        param.showName = this.tagData.data.submit.content.showName;
      }
    }
    this.params.content = param;
    this.params.id = this.tagData.data.submit.id;

    this.params.content.pageNo = this.pageNo;
    this.params.sessionId = localStorage.getItem("sessionId");
    this.httpService.post('application/submit', this.params, res => {
      if (res.success) {
        if (res.data.submit) {
          this.tagData.data.submit = res.data.submit;
          this.params = res.data.submit; // 为了每次刷新下一页的参数 "oldIndex"
        }
        this.tagData.data.data = [];
        const result = res.data.data; // JSON.parse(res.data.data);
        this.tagData.data.data = result;
        if (res.data.moreButton) {
          this.tagData.data.moreButton = res.data.moreButton;
        }
        this.pageTotal = this.tagData.pageTotal;

        this.showLoadMore = !this.tagData.data.moreButton && this.tagData.data.submit && this.pageTotal && (this.pageNo < Math.ceil(this.pageTotal / this.pageSize)) && this.tagData.asyncShow !== 'true';

      } else {
        // 请求数据失败
        this.tagData.data.data = [];
        // this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    },
      err => {
        // 请求数据失败
        this.tagData.data.data = [];
        // this.appGlobalService.showToast(err.message, 2000, 'middle');
      });
  }
  openPage(link, i) {
    if (link) {
      const that = this;
      this.appGlobalService.commentsListIndex = i;
      this.pageModalService.openPage(link, '', res => {
        if (res) {
          that.updateItem(i);
        }
      });
    }

  }


  async presentAction() {
    const buttonsArr = [
      {
        text: "取消",
        cssClass: ["action-sheet-font-color", "action-sheet-font-top"],
        handler: () => {
          actionSheet.dismiss();
        }
      }
    ];
    if (this.phoneArray[1]) {
      buttonsArr.unshift({
        text: this.phoneArray[1],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(Number(this.phoneArray[1]));
        }
      });
    }

    if (this.phoneArray[0]) {
      buttonsArr.unshift({
        text: this.phoneArray[0],
        cssClass: ["action-sheet-font-color"],
        handler: () => {
          this.presentAlertConfirm(this.phoneArray[0]);
        }
      });
    }

    const actionSheet = await this.actionSheetCtrl.create({
      mode: "md",
      cssClass: "match-padding",
      buttons: buttonsArr
    });
    await actionSheet.present();
  }

  async presentAlertConfirm(mobile, name?) {
    const msg = (name ? name + ' ' : '') + mobile;
    const alert = await this.alertController.create({
      header: this.tagData.nickName,
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "拨打",
          handler: () => {
            this.httpService.changeCallNumber(mobile);
          }
        }
      ]
    });

    await alert.present();
  }

  submitAction(btn) {

    let submit = btn.submit;
    const params = {
      content: submit.content,
      id: submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      this.appGlobalService.showToast(res.message, 1500, "middle");
      if (res.success) {
        if (submit.content !== undefined && submit.content.btnId !== undefined) {
          const btnId = submit.content.btnId;
          $('#' + btnId).click();
        } else {
          // const tabIndex = parseInt(item.tabClick);
          // if (item.tabClick) {
          //   setTimeout(() => {
          //     this.eventService.eventEmit.emit("topTabChangeByIndex", tabIndex);
          //   }, 1000);
          // }          
        }

      }
    });
  }
  del(item, dataIndex) {
    // 删除
    const params = {
      content: item.submit.content,
      id: item.submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      this.appGlobalService.showToast(res.message, 1500, "middle");
      if (res.success) {
        if (dataIndex >= 0 && dataIndex < this.tagData.data.data.length) {
          this.tagData.data.data.splice(dataIndex, 1);
        }
      }
    });
  }

  iconClick(item, dataIndex?, e?, tagDataIndex?) {
    if (e) {
      e.stopPropagation();
    }
    if(tagDataIndex !== undefined) {
      this.appGlobalService.commentsListIndex = tagDataIndex;
    }
    if (item.modelType === "iconLink") {
      this.pageModalService.openPage(item.link);
    }
    if (item.modelType === "pageModal") {
      this.pageModalService.openPage(item.link, '', res => {
        if (res) {
          this.updateItem();
        }
      });
    }
    if (item.modelType === "iconSubmit") {
      let submit;
      if (item.button && item.button.submit) {
        submit = item.button.submit;
      } else if (item.submit) {
        submit = item.submit;
      }
      const params = {
        content: submit.content,
        id: submit.id,
        sessionId: localStorage.getItem("sessionId")
      };
      this.httpService.post("application/submit", params, res => {
        this.appGlobalService.showToast(res.message, 1500, "middle");
        if (res.success) {
          if (submit.content !== undefined && submit.content.btnId !== undefined) {
            const btnId = submit.content.btnId;
            $('#' + btnId).click();
          } else {

            if (item.refresh !== undefined) {
              this.appGlobalService.reloadCurrentPage();
            }
            if (item.link && item.link.target) {
              const pageParams = {
                pageId: item.link.target,
                params: item.link.params ? item.link.params : {},
                sessionId: localStorage.getItem("sessionId")
              };
              this.appGlobalService.goToForward(pageParams);
            }

            if(res.data && res.data.eventResult !== undefined) {
              if(res.data.eventResult === "false") {
                item.iconName = 'https://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_1683356627189868ce62f30825acfde3a6b9224a96f8e.png';
                if (item.tip > 0) {
                  item.tip = Number(item.tip) - 1;
                  if(item.tip <= 0) {
                    item.tip = '点赞'
                  }
                }
              } else if(res.data.eventResult === "true") {
                item.iconName = 'https://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_16835103291584a0c8015c6cfed9f472d192d8b6ff42b.png';
                if (isNaN(Number(item.tip))) {
                  item.tip = 1;
                } else {
                  item.tip = Number(item.tip) + 1;
                }

              }
            }
          }

        }
      });
    }
    // 1.6.21 复制按钮
    if (item.modelType === 'copy') {
      this.shareService.copyUrl(item.msg);
    }
    // 1.7.0 新增弹窗
    if (item.modelType === 'question') {
      this.presentQuestion(item, item.msg, dataIndex);
    }

    if (item.modelType === "phone") {
      // 电话
      this.phoneArray = item.phone.split(",");
      if (this.phoneArray.length > 1) {
        this.presentAction();
      } else {
        this.presentAlertConfirm(Number(this.phoneArray[0]), item.label);
      }
    }
  }

  async presentQuestion(itemObj, msg, dataIndex) {

    const alert = await this.alertController.create({
      header: '',
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "确定",
          handler: () => {
            let submitParam;
            if (itemObj.submit) {
              submitParam = itemObj.submit;
            } else if (itemObj.button) {
              submitParam = itemObj.button.submit;
            }
            const params = {
              content: submitParam.content,
              id: submitParam.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              this.appGlobalService.showToast(res.message, 1500, "middle");
              if (res.success) {
                if (itemObj.refresh !== undefined) {
                  this.appGlobalService.reloadCurrentPage();
                } else {
                  if (dataIndex >= 0 && dataIndex < this.tagData.data.data.length) {
                    this.tagData.data.data.splice(dataIndex, 1);
                  }
                  if (this.tagData.data.data.length === 0) {
                    //1.7.0 新增
                    this.tagData.data.moreButton = {};
                  }
                }
              }
            });
          }
        }
      ]
    });

    await alert.present();
  }



  showAll(item, e) {
    if(e) {
      e.stopPropagation();
    }
    item.show = !item.show;
    if (item.show) {
      item.showText = '收起';
    } else {
      item.showText = '查看全部';
    }
  }
  updateItem(i?) {
    // if (this.checkAll) {
    //   this.appGlobalService.reloadCurrentPage();
    //   return;
    // }
    const that = this;

    if (!this.tagData.data.data[i].id) {
      return;
    }
    if (that.tagData.data.data[i].updateItemType !== undefined
      && that.tagData.data.data[i].updateItemType === 'delete') {
      that.tagData.data.data.splice(i, 1);
      return;
    }
    const page: any = this.appGlobalService.getCurrentTarget();
    if (page.params) {
    } else {
      page.params = {}
    }
    page.params.id = this.tagData.data.data[i].id;
    this.httpService.post('application/page', page, async res => {
      const tagData = JSON.parse(res.script).views[0].tags;
      tagData.forEach(element => {
        if (element.style === 'commentsListTag' && element.data && element.data.data[0]) {
          that.tagData.data.data.splice(i, 1, element.data.data[0]);
        }

      });
    });
  }

  // updateItem() {
  //   if (this.checkedAll) {
  //     this.appGlobalService.reloadCurrentPage();
  //     return;
  //   }
  //   const that = this;
  //   const page: any = this.appGlobalService.getCurrentTarget();
  //   if (page.params) {
  //   } else {
  //     page.params = {};
  //   }
  //   page.params.id = this.ids;
  //   this.http.post('application/page', page, async res => {
  //     const tagData = JSON.parse(res.script).views[0].tags;
  //     tagData.forEach(element => {
  //       if (element.style === 'auditListTag' && element.data && element.data.data) {
  //         element.data.data.forEach(newItem => {
  //           that.tagData.data.data.forEach(oItem => {
  //             if (oItem.id === newItem.id) {
  //               const index = that.tagData.data.data.indexOf(oItem);
  //               that.tagData.data.data.splice(index, 1, newItem)//替换
  //             }
  //           });
  //         });
  //       }
  //       that.checkAll();

  //     });
  //   });
  // }


  loadMoreData(event) {
    try {
      this.params = { content: {} };
      this.params = this.tagData.data.submit;
      this.pageNo = this.pageNo + 1;
      // // 参数
      this.params.content.pageNo = this.pageNo;
      this.params.id = this.tagData.data.submit.id;
      this.params.sessionId = localStorage.getItem("sessionId");
      // 请求获取新数据
      this.httpService.post('application/submit', this.params, res => {

        // 请求数据成功
        if (res.success) {
          if (res.data.submit) {
            this.params = res.data.submit; // 为了每次刷新下一页的参数 "oldIndex"
          }
          const resList = res.data.data;
          // 追加返回数据
          if (resList && resList.length > 0) {
            // 追加数据
            resList.map(v => {
              this.tagData.data.data.push(v);
            });
          } else {
            event.target.disabled = true;
            this.showLoadMore = false;
          }
        } else {
          // 请求失败，更新当前页数
          this.pageNo = this.pageNo - 1;
          // 请求数据失败
          // this.appGlobalService.showToast(res.message, 2000, 'middle');
        }
        event.target.complete();

      }, err => {
        // 请求失败，更新当前页数
        this.pageNo = this.pageNo - 1;
        // 请求数据失败
        // this.appGlobalService.showToast(err.message, 2000, 'middle');
        event.target.complete();

      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }


  choose(item) {
    item.checked = !item.checked;
    this.checkAll();
  }
  // 检查是否已经全选
  checkAll() {
    // max 10
    if (this.tagData.data.chooseSubmit && this.tagData.data.chooseSubmit.type && this.tagData.data.chooseSubmit.type === 'ljpopup') {
      this.tagData.data.chooseSubmit.maxRow = this.tagData.data.chooseSubmit.maxRow > 0 ? this.tagData.data.chooseSubmit.maxRow : 10;
      let count = 0;
      this.tagData.data.data.forEach(element => {
        if (element.checked) {
          ++count;
          if (count > this.tagData.data.chooseSubmit.maxRow) {
            element.checked = false;
            this.appGlobalService.showToast('最多只能选择' + this.tagData.data.chooseSubmit.maxRow + '个', 2000, 'middle');
          }
        }
      });
    } else {
      let all = true;
      this.tagData.data.data.forEach(element => {
        if (!element.checked) {
          all = false;
        }
      });
      this.eventService.eventEmit.emit('chooseAllResult', all);
    }
  }

  async popup(item, e, data) {
    if(e) {
      e.stopPropagation();
    }
    if (data.firstRowLeft && data.firstRowLeft.link) {
      this.pageModalService.openPage(data.firstRowLeft.link.link);
    } else {
      const modal = await this.modalController.create({
        component: VideoImgPopupComponent ,
        componentProps: { tagData: item, style: this.tagData.style}
      });
      return await modal.present();
    }
    
  }

  careBtn(item,submit,e){
    if(e) {
      e.stopPropagation();
    }
    const params = {
      content: submit.content,
      id: submit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {
      if (res.success) {
        if (res.data && res.data.eventResult !== undefined && res.data.eventResult === 'true') {
          item.state = '1';
          item.label = '已关注';
          this.tagData.data.data.forEach(e => {
            if (e.firstRowRight && e.firstRowRight.fourthText && e.firstRowRight.fourthText.submit &&
              e.firstRowRight.fourthText.submit.content.interest_user_id === submit.content.interest_user_id) {
              e.firstRowRight.fourthText.state = '1';
              e.firstRowRight.fourthText.label = '已关注';
            }
          })
        } else if(res.data && res.data.eventResult !== undefined && res.data.eventResult === 'false') {
          item.state = '0';
          item.label = '关注';
          this.tagData.data.data.forEach(e => {
            if (e.firstRowRight && e.firstRowRight.fourthText && e.firstRowRight.fourthText.submit &&
              e.firstRowRight.fourthText.submit.content.interest_user_id === submit.content.interest_user_id) {
              e.firstRowRight.fourthText.state = '0';
              e.firstRowRight.fourthText.label = '关注';
            }
          })
        }
      }
    });
  }

  ngOnDestroy(): void {
    this.eventService.removeCustomListListeners();
    const description = document.getElementById("html2canvas");
    description.innerHTML = '';
    description.style.width = '100VW';
    description.style.padding = '0rem';
    description.style.fontSize = '0.94rem';
    description.style.lineHeight = '1.31rem';
  }
}


